<template style="height: 100%;">
  <el-container>
    <el-aside width="240px" style="overflow: auto">
      <div style="height: 100px; width: 100%">
        <div
          class="block"
          v-for="a in list"
          :key="a.id"
          @click="click(a)"
          style="margin: 0; padding: 0"
        >
          <el-card
            shadow="hover"
            style="margin-top: 10px; height: 100%; width: 163%"
          >
            <el-badge
              :value="a.count == 0 ? null : a.count"
              style="margin-right: 40px"
            >
              <div>
                <el-row :gutter="24" style="width: 150%">
                  <el-col :span="8">
                    <el-avatar
                      shape="square"
                      fit="contain"
                      :src="a.isGroup ? a.data.picture : a.data.headPortrait"
                    ></el-avatar>
                  </el-col>
                  <el-col :span="12"
                    ><h4>{{ a.data.name }}</h4>
                  </el-col>
                  <el-col :span="2">
                    <i class="el-icon-s-grid" @click="GroupAdminClick(a)"></i
                  ></el-col>
                </el-row>
              </div>
            </el-badge>
          </el-card>
        </div>
      </div>
    </el-aside>
    <el-main
      style="background-color: aliceblue"
      v-show="this.groupData != null"
    >
      <div class="shouData" style="overflow: auto" ref="shouData">
        <div v-for="data in chatDataList" :key="data.id">
          <div
            :class="{
              'message-box': true,
              'message-box-reverse': chatData.sendId === data.sendId,
            }"
          >
            <div>
              <!-- 头像 -->
                <!-- v-if="chatData.sendId === data.sendId" -->
              <el-image
                :src="data.headPortrait"
                :preview-src-list="[data.headPortrait]"
                style="height: 50px; width: 50px"
              />
            </div>
            <div class="message-body">
              <div>{{ data.name }}</div>
              <div><p v-if="data.marking === 0" class="pp1">{{ data.data }}</p>
              <el-card
                v-else-if="data.marking === 1"
                style="max-width: 200px"
                shadow="hover"
              >
                <div @click="downloadFile(data)">{{ data.fileName }}</div>
              </el-card>
              <el-image
                v-else-if="data.marking === 2"
                :src="data.data"
                style="max-width: 300px; max-height: 300px"
                :preview-src-list="[data.data]"
              >
              </el-image>
              <video
                v-else-if="data.marking === 4"
                width="450"
                height="320"
                controls
              >
                <source :src="data.data" type="video/mp4" />
              </video></div>
            </div>
          </div>
        </div>
      </div>
      <div class="shouUtil">
        <div style="height: 20%; width: 100%">
          <el-upload
            ref="addGroupData"
            class="avatar-uploader"
            :action="host + 'api/File/Uploading'"
            :show-file-list="false"
            :headers="headers"
            :auto-upload="true"
            style="float: left"
            :on-success="uploadFiles"
          >
            <el-button type="primary"
              >上传文件<i class="el-icon-upload el-icon--right"></i
            ></el-button>
          </el-upload>
          <el-upload
            ref="addGroupData"
            :action="host + 'api/File/Uploading'"
            :show-file-list="false"
            style="float: left"
            :headers="headers"
            :auto-upload="true"
            :before-upload="imaType"
            :on-success="uploadPictures"
          >
            <el-button type="primary"
              >发送图片<i class="el-icon-picture"></i
            ></el-button>
          </el-upload>
          <span style="float: right"
            ><el-button
              @keyup.enter="chatSend"
              @click="chatSend"
              :disabled="chatData.data == ''"
              >发送</el-button
            ></span
          >
        </div>
        <div style="height: 85%">
          <el-input
            type="textarea"
            :autosize="{ minRows: 9, maxRows: 9 }"
            resize="none"
            placeholder="请输入发送内容"
            v-model="chatData.data"
            clearable
            height="100%"
          >
          </el-input>
        </div>
      </div>
    </el-main>
    <el-drawer
      :title="groupAdminData.data.name"
      :visible.sync="GroupAdminVisible"
      direction="rtl"
      :before-close="
        () => {
          GroupAdminVisible = false;
        }
      "
    >
      <div style="width: 100%">
        <el-row style="overflow: auto; height: 300px">
          <el-col :span="6" v-for="o in groupdLists" :key="o.id">
            <el-tooltip
              class="item"
              effect="dark"
              :content="'昵称：' + o.self.name"
              placement="top-start"
            >
              <el-card
                :body-style="{ padding: '0px' }"
                style="
                  height: 80px;
                  width: 80px;
                  margin-top: 2px;
                  margin-bottom: 2px;
                "
                shadow="hover"
              >
                <img
                  :src="o.self.headPortrait"
                  style="height: 80px; width: 80px"
                  fit="fill"
                  :lazy="true"
                />
              </el-card>
            </el-tooltip>
          </el-col>
          <el-col :span="6">
            <el-tooltip
              class="item"
              effect="dark"
              content="添加群成员"
              placement="top-start"
            >
              <el-card
                :body-style="{ padding: '0px' }"
                style="
                  height: 80px;
                  width: 80px;
                  margin-top: 2px;
                  margin-bottom: 2px;
                "
                shadow="hover"
                @click="addGroupVisible"
              >
                <i
                  class="el-icon-plus avatar-uploader-icon"
                  style="height: 80px; width: 80px; margin-top: 25px"
                  @click="addGroupVisible"
                ></i>
              </el-card>
            </el-tooltip>
          </el-col>
        </el-row>
      </div>
      <el-button
        type="primary"
        :v-show="groupAdminData.data.selfId == this.chatData.sendId"
        style="width: 100%"
        @click="deleteGroupVisible = true"
        >删除群</el-button
      >
    </el-drawer>
    <el-dialog title="提示" :visible.sync="addGroupVisibles" width="45%" center>
      <el-transfer
        v-model="groupAdmin.data"
        :data="groupAdmin.list"
        :button-texts="['删除群成员', '添加群成员']"
        :titles="['好友列表', '群成员']"
      ></el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGroupVisibles = false">取 消</el-button>
        <el-button type="primary" @click="addGroups">确 定</el-button>
      </span>
    </el-dialog>
    <el-drawer
      title="好友信息"
      :visible.sync="friendAdminVisible"
      direction="rtl"
      :before-close="
        () => {
          friendAdminVisible = false;
        }
      "
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="6">
          <el-image
            style="width: 100px; height: 100px"
            :src="friendAdmin.headPortrait"
            fit="fill"
          ></el-image>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="6" style="height: 50px">
          <el-tag type="success">{{ friendAdmin.name }}</el-tag>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="height: 50px">
        <el-col :span="12" :offset="6">
          <el-button
            type="danger"
            @click="
              () => {
                deleteFriendVisible = true;
              }
            "
            >删除好友</el-button
          >
        </el-col>
      </el-row>
      <el-dialog
        title="删 除 警 告"
        :visible.sync="deleteFriendVisible"
        width="30%"
        :before-close="
          () => {
            deleteFriendVisible = false;
          }
        "
      >
        <span>你确定删除{{ friendAdmin.name }}?删除操作无法撤销！！！</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteFriendVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteFriend">确 定</el-button>
        </span>
      </el-dialog>
    </el-drawer>
    <el-dialog
      title="删 除 警 告"
      :visible.sync="deleteGroupVisible"
      width="30%"
      :before-close="
        () => {
          deleteGroupVisible = false;
        }
      "
    >
      <span>你确定删除?删除操作无法撤销！！！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteGroupVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteGroup(groupAdminData.data.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-container>
</template>
<script>
import { GetChatMessageDataList } from "../config/ChatMessage";
import { get, Downloads, post, del } from "../util/request";
import { GetGroupMembersList, AddGroup } from "../config/groupMembers";
import { host } from "../config/config";
import { GetGroup, DeleteGroupData } from "../config/Group";
import { GetFriendsDtos, DeleteFriends } from "../config/Friends";
import EventBus from "../../msg";
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      deleteGroupVisible: false,
      deleteFriendVisible: false,
      friendAdmin: {},
      GroupAdminVisible: false,
      groupAdmin: {
        list: [],
        data: [],
      },
      friendAdminVisible: false,
      addGroupVisibles: false,
      list: [],
      groupAdminData: {
        isGroup: false,
        key: 0,
        selfId: "",
        data: {
          id: "",
          name: "",
          notice: "",
          picture: "",
          pictureKey: "",
          selfId: "",
        },
        id: "",
        chatId: "",
      },
      groupdLists: null,
      groupData: null,
      host: host,
      friendsList: [],
      chatTimer: null,
      chatDataList: [],
      iswatch: false,
      chatData: {
        data: "",
        fileName: "",
        sendId: "",
        marking: 0,
        receiving: "",
      },
      GetChatDataList: {
        receiving: "",
        pageNo: 1,
        pageSize: 40,
      },
      src: [
        "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
      ],
    };
  },
  watch: {
    chatDataList: function() {
      this.$nextTick(function() {
        if (this.iswatch) {
          this.$refs.shouData.scrollTop = this.$refs.shouData.scrollHeight;
          this.iswatch = null;
        } else if (this.iswatch != null) {
          this.iswatch = true;
        }
      });
    },
  },
  mounted() {
    this.$refs.shouData.addEventListener(
      "scroll",
      () => {
        if (this.$refs.shouData.scrollTop === 0 && !this.iswatch) {
          this.GetChatDataList.pageNo += 1;
          this.GetChatMessageDataList();
        }
      },
      false
    );
  },
  methods: {
    GetChatMessageDataList() {
      get(GetChatMessageDataList, this.GetChatDataList).then((response) => {
        if (response.statusCode === 200) {
          if (response.value.length == 0) {
            if (this.GetChatDataList.pageNo > 1) {
              this.GetChatDataList.pageNo = this.GetChatDataList.pageNo - 1;
            }
          } else {
            for (let i = 0; i < response.value.length; i++) {
              this.chatDataList.unshift(response.value[i]);
            }
          }
        }
      });
    },
    deleteGroup(id) {
      del(DeleteGroupData + "?id=" + id).then((response) => {
        if (response.statusCode === 200) {
          this.$message.success("删除成功");
          this.GroupAdminVisible = false;
          this.deleteGroupVisible = false;
          this.GetFriends();
          this.getGroupList();
          this.groupData = null;
        } else {
          this.$message.error(response.value.message);
        }
      });
    },
    deleteFriend() {
      del(DeleteFriends + "?friendId=" + this.friendAdmin.id).then(
        (response) => {
          this.deleteFriendVisible = false;
          if (response.statusCode === 200) {
            this.$message.success("删除成功");
            this.getGroupList();
          } else {
            this.$message.error(response.message);
          }
        }
      );
    },
    addGroups() {
      if (this.groupAdmin.data.length <= 0) return;
      console.log(this.groupAdmin);
      post(
        AddGroup + "?groupId=" + this.groupData.data.id,
        this.groupAdmin.data
      ).then((response) => {
        this.addGroupVisibles = false;
        if (response.statusCode === 200) {
          this.$message.success("添加成功");
          this.GetGroupData();
        } else {
          this.$message.error(response.message);
        }
        console.log("添加群成员", response);
      });
    },
    addGroupVisible() {
      this.addGroupVisibles = true;
      const friends = this.friendsList;
      var friendsData = this.groupdLists;
      console.log("friends", friendsData);
      if (this.groupAdmin.list.length != 0) {
        this.groupAdmin.list.length = 0;
        this.groupAdmin.data.length = 0;
      }
      for (let i = 0; i < friends.length; i++) {
        console.log("friendsData", friendsData);
        console.log(friends[i]);
        if (!friendsData.find((a) => a.selfId === friends[i].friendId)) {
          this.groupAdmin.list.push({
            key: friends[i].friend.id,
            label: friends[i].friend.name,
          });
        }
      }
    },
    GetFriends() {
      get(GetFriendsDtos).then((response) => {
        if (response.statusCode === 200) {
          this.friendsList = response.value;
        } else {
          this.$message.error(response.message);
        }
      });
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    GroupAdminClick(a) {
      this.groupAdminData = a;
      console.log(a);
      if (a.isGroup == true) {
        this.GroupAdminVisible = true;
        this.GetGroupData();
      } else {
        this.friendAdminVisible = true;
        this.friendAdmin = a.data;
      }
    },
    GetGroupData() {
      get(GetGroup + "?id=" + this.groupAdminData.data.id).then((response) => {
        if (response.statusCode === 200) {
          this.groupdLists = response.value.groupMembers;
        }
      });
    },
    downloadFile(data) {
      console.log(data);
      Downloads(data.data).then((response) => {
        console.log(response);
      });
    },
    change() {
      // this.addGroupData.picture = URL.createObjectURL(file.raw);
    },
    uploadPictures(response) {
      if (response.statusCode === 200) {
        var path = response.value;
        this.chatData.data = path;
        var name = path.split("file/")[1].split(".");
        if (name[1] == "mp4") {
          this.chatData.marking = 4;
        } else {
          this.chatData.marking = 2;
        }
        if (this.groupData.isGroup == true) {
          this.connectionSignalR.send("SendGroup", this.chatData);
          this.chatData.data = "";
        } else {
          this.connectionSignalR.send("Message", this.chatData);
          this.chatData.data = "";
        }
      } else {
        this.$message.error(response.message);
      }
    },
    uploadFiles(response) {
      if (response.statusCode === 200) {
        var path = response.value.path;
        this.chatData.data = path;
        this.chatData.fileName = path.split("file/")[1];
        this.chatData.marking = 1;
        if (this.groupData.isGroup == true) {
          this.connectionSignalR.send("SendGroup", this.chatData);
          this.chatData.data = "";
        } else {
          this.connectionSignalR.send("Message", this.chatData);
          this.chatData.data = "";
        }
      } else {
        this.$message.error(response.message);
      }
    },
    imaType(file) {
      console.log(file);
      var name = file.name.split(".");
      var isTrue = false;
      var ima = ["jpg", "jpeg", "gif", "tiff", "bmp", "png", "mp4"];
      for (let i = 0; i < ima.length; i++) {
        if (ima[i] == name[name.length - 1]) {
          isTrue = true;
          break;
        }
      }
      if (isTrue != true) {
        this.$message.error("上传错误，只能是图片格式");
        return false;
      }
    },
    chatSend() {
      if (this.groupData.isGroup == true) {
        this.chatData.marking = 0;
        this.connectionSignalR.send("SendGroup", this.chatData);
        this.chatData.data = "";
      } else {
        this.chatData.marking = 0;
        this.connectionSignalR.send("Message", this.chatData);
        this.chatData.data = "";
      }
    },
    getGroupList() {
      get(GetGroupMembersList).then((response) => {
        if (response.statusCode === 200) {
          this.list = response.value;
          var list = this.list;
          for (let i = 0; i < list.length; i++) {
            if (list[i].isGroup == true) {
              this.groupDatas[i] = {
                receiving: list[i].data.receiving,
                chat: [],
              };
            } else {
              this.groupDatas[i] = { receiving: list[i].receiving, chat: [] };
            }
          }
        }
      });
    },
    click(a) {
      if (this.chatTimer != null) window.clearInterval(this.chatTimer);
      this.groupData = a;
      this.GetChatDataList.pageNo = 1;
      this.iswatch = false;
      this.GroupAdmin = this.groupData;
      this.chatData.receiving = a.receiving;
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].key == a.key) {
          var isData = this.list[i];
          var top = this.list[0];
          isData.count = 0;
          this.list[0] = isData;
          this.list[i] = top;
          for (let i = 0; i < this.groupDatas.length; i++) {
            if (this.groupDatas[i].receiving == a.receiving) {
              this.GetChatDataList.receiving = a.receiving;
              this.chatDataList = [];
              this.GetChatMessageDataList();
              break;
            }
          }
          this.$forceUpdate();
          break;
        }
      }
    },
  },
  created() {
    var user = JSON.parse(sessionStorage.getItem("user"));
    this.chatData.sendId = user.id;
    this.GetFriends();
    this.getGroupList();
    EventBus.$on("ChatRefresh", (data) => {
      if (data.systemMarking === 2) {
        this.getGroupList();
      }
    });
    EventBus.$on("chatData", (receiving, data) => {
      if (this.chatData.receiving == receiving) {
        this.chatDataList.push(data);
        var This = this;
        window.setTimeout(() => {
          This.$refs.shouData.scrollTop = This.$refs.shouData.scrollHeight;
        }, 50);
      }
      for (let i = 0; i < this.list.length; i++) {
        if (
          this.list[i].receiving == receiving &&
          this.chatData.receiving != receiving
        ) {
          this.list[i].count++;
        }
      }
    });
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.chatQ {
  background-color: lime;
}
.shouUtil {
  height: 30%;
  width: 100%;
}
.shouData {
  height: 70%;
  width: 100%;
}
.block {
  width: 135px;
  height: 80px;
}

.pp1 {
  background-color: forestgreen;
  padding: 5px 8px;
  display: inline-block;
  border-radius: 4px;
  margin: 0px 0 0px 0px;
  position: relative;
  max-width: 650px;
  word-wrap: break-word;
  word-break: break-all;
}
.chatTiltle {
  display: block;
  height: 20px;
  position: relative;
  top: -20px;
  text-align: center;
}

.message-box {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin: 8px;
}
.message-box-reverse {
  flex-direction: row-reverse;
}
.message-body {
  margin-right: 4px;
  display: flex;
  flex-direction: column;
}
.message-box-reverse > .message-body {
  margin-left: 4px;
  align-items: flex-end;
}
</style>
